<template>
  <view class="container">
    <!-- 身份选择 -->
    <view class="role-tabs">
      <button class="role-btn" :class="{ active: formData.role === 'admin' }" @click="changeRole('admin')">管理员</button>
      <button class="role-btn" :class="{ active: formData.role === 'user' }" @click="changeRole('user')">用户</button>
    </view>

    <!-- 登录表单 -->
    <template v-if="!isRegister">
      <view class="form-item">
        <text class="label">账号<text class="required">*</text></text>
        <uni-easyinput v-model="formData.userName" placeholder="请输入账号" maxlength="18" />
      </view>

      <view class="form-item">
        <text class="label">密码<text class="required">*</text></text>
        <uni-easyinput type="password" v-model="formData.password" placeholder="请输入密码" maxlength="18" />
      </view>

      <view class="btn-group">
        <button class="submit-btn" @click="handleLogin">登录</button>
        <text class="switch-text" @click="changeForm(true)">去注册>></text>
      </view>
    </template>

    <!-- 注册表单 -->
    <template v-else>
      <view class="form-item">
        <text class="label">账号<text class="required">*</text></text>
        <uni-easyinput v-model="formData.userName" placeholder="请输入账号" maxlength="18" />
      </view>

      <view class="form-item">
        <text class="label">密码<text class="required">*</text></text>
        <uni-easyinput type="password" v-model="formData.password" placeholder="请输入密码" maxlength="18" />
      </view>

      <view class="form-item">
        <text class="label">确认密码<text class="required">*</text></text>
        <uni-easyinput type="password" v-model="formData.confirmPassword" placeholder="请再次输入密码" maxlength="18" />
      </view>

      <view class="btn-group">
        <button class="submit-btn" @click="handleRegister">注册</button>
        <text class="switch-text" @click="changeForm(false)">去登录>></text>
      </view>
    </template>
  </view>
</template>

<script setup>
import { nextTick, ref } from "vue";
import { showToast, getStorage } from "@/utils/common";
import { userRegister, userLogin, userChecktoken } from "@/api/user";
import { useUserStore } from "@/store/user";
import { onLoad } from "@dcloudio/uni-app";

const userStore = useUserStore();

const isRegister = ref(false);
const formData = ref({
  role: "user",
  userName: "",
  password: "",
  confirmPassword: "",
});

// 切换角色
const changeRole = (role) => {
  formData.value.role = role;
};

// 切换表单
const changeForm = (value) => {
  resetForm();
  isRegister.value = value;
};

// 清空
const resetForm = () => {
  formData.value = {
    ...formData.value,
    userName: "",
    password: "",
    confirmPassword: "",
  };
};

// 登录验证
const handleLogin = async () => {
  if (!formData.value.userName || !formData.value.password) {
    showToast("账号或密码不能为空");
    return;
  }

  try {
    const res = await userLogin({
      userName: formData.value.userName,
      password: formData.value.password,
      roleType: formData.value.role == "admin" ? 0 : "1",
    });
    uni.showLoading({
      title: "", // 加载提示文字
      mask: true, // 显示透明蒙层，防止用户点击
    });
    if (res.code == 200) {
      userStore.setProfile({
        ...res.data.info,
        token: res.data.token,
      });
      userStore.setToken(res.data.token);
      showToast(res.msg);
      nextTick(() => {
        if (res.data.info.roleType == "0") {
          uni.setTabBarItem({
            index: 1,
            text: "用户",
          });
        } else {
          uni.setTabBarItem({
            index: 1,
            text: "题库",
          });
        }
        uni.reLaunch({
          url: "/pages/home/index",
        });
      }, 100);
    }
    uni.hideLoading();
  } catch (error) {
    console.log(error);
    uni.hideLoading();
  }
};

// 注册验证
const handleRegister = async () => {
  if (!formData.value.userName || !formData.value.password || !formData.value.confirmPassword) {
    showToast("账号或密码不能为空");
    return;
  }

  if (formData.value.password !== formData.value.confirmPassword) {
    showToast("两次密码输入不一致");
    return;
  }
  try {
    const res = await userRegister({
      userName: formData.value.userName,
      password: formData.value.password,
      roleType: formData.value.role == "admin" ? 0 : "1",
    });
    if (res.code == 200) {
      showToast(res.msg);
      resetForm();
      isRegister.value = false;
    }
  } catch (error) {
    showToast(res.msg);
    console.log(error);
  }
};

onLoad(async () => {
  const token = getStorage("token");
  if (token) {
    userStore.setToken(token);
    const res = await userChecktoken({ token });
    if (res.code == 200) {
      userStore.setProfile({
        ...res.data.info,
        token: res.data.token,
      });
      userStore.setToken(res.data.token);
      showToast(res.msg);
      nextTick(() => {
        if (res.data.info.roleType == "0") {
          uni.setTabBarItem({
            index: 1,
            text: "用户",
          });
        } else {
          uni.setTabBarItem({
            index: 1,
            text: "题库",
          });
        }
        uni.reLaunch({
          url: "/pages/home/index",
        });
      });
    }
  }
});
</script>

<style lang="scss">
.container {
  padding: 60rpx 40rpx;
  font-size: 24rpx;
  color: #333;

  .role-tabs {
    display: flex;
    justify-content: center;
    margin-bottom: 60rpx;

    .role-btn {
      width: 200rpx;
      height: 80rpx;
      line-height: 80rpx;
      margin: 0 20rpx;
      border-radius: 10rpx;
      background-color: #f5f5f5;
      color: #666;
      font-size: 24rpx;

      &.active {
        background-color: #007aff;
        color: white;
      }
    }
  }

  .form-item {
    margin-bottom: 40rpx;

    .label {
      display: block;
      margin-bottom: 20rpx;
    }

    .required {
      color: red;
      margin-left: 10rpx;
    }
  }

  .btn-group {
    margin-top: 60rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;

    .submit-btn {
      width: 300rpx;
      height: 80rpx;
      line-height: 80rpx;
      background-color: #007aff;
      color: white;
      border-radius: 10rpx;
    }

    .switch-text {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      color: #007aff;
      text-decoration: underline;
    }
  }
}
</style>
